package com.hmily.spring.samples.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Set;

/**
 * <h1>想办法将URL注册到Spring容器中即想办法将URL与CommonController进行关联.</h1>
 *
 * @author hmilyylimh
 * ^_^
 * @version 0.0.1
 * ^_^
 * @date 2021-10-30
 */
@Configuration
public class ControllerConfig {

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;
    @Autowired
    private CommonController commonController;

    /**
     * <h2>想办法将 URL 注册到Spring容器中。</h2>
     */
    @PostConstruct
    public void init(){
        // 获取所有的URL，这里的URL可以从远端想办法获取下来
        Set<String> urlSet = CommonController.URL_MAP.keySet();
        // 这里获取的是通用处理所有请求的那个方法
        Method method = ReflectionUtils.findMethod(CommonController.class,
                "request",
                HttpServletRequest.class,
                HttpServletResponse.class);
        // 这里获取的是需要处理什么形式的请求，比如POST、GET、PUT 等等
        RequestMethod postMethod = RequestMethod.valueOf("POST");

        // 真正的将URL注册到Spring中
        for (String path : urlSet) {
            RequestMappingInfo mappingInfo = RequestMappingInfo.paths(path).methods(postMethod).build();

            requestMappingHandlerMapping.registerMapping(
                    mappingInfo,
                    commonController,
                    method
            );
        }
    }
}
